import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 100;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("InheritedWidget")),
        body: CounterWidget(
          counter: _counter,
          child: Center(
            child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              ShowData1(),
              ShowData2(),
            ]),
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              _counter++;
            });
          },
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

class CounterWidget extends InheritedWidget {
  final int counter;

  const CounterWidget({
    Key? key,
    required Widget child,
    this.counter = 0,
  }) : super(key: key, child: child);

  static CounterWidget of(BuildContext context) {
    final CounterWidget? result = context.dependOnInheritedWidgetOfExactType<CounterWidget>();
    assert(result != null, 'No CounterWidget found in context');
    return result!;
  }

  @override
  bool updateShouldNotify(CounterWidget old) {
    return old.counter != counter;
  }
}

class ShowData1 extends StatefulWidget {
  const ShowData1({Key? key}) : super(key: key);

  @override
  State<ShowData1> createState() => _ShowData1State();
}

class _ShowData1State extends State<ShowData1> {
  @override
  Widget build(BuildContext context) {
    return Card(
        color: Colors.green,
        child: Text(
          "当前计数：${CounterWidget.of(context).counter}",
          style: TextStyle(fontSize: 30),
        ));
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("CounterWidget updateShouldNotify 返回 true 触发了 didChangeDependencies");
  }
}

class ShowData2 extends StatelessWidget {
  const ShowData2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
        color: Colors.redAccent,
        child: Text(
          "当前计数：${CounterWidget.of(context).counter}",
          style: TextStyle(fontSize: 30),
        ));
  }
}
